package com.mdr.imedera.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @Author wxb
 * @Datatime 2020/10/21 16:38
 * @Descript
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    //定义静态的ApplicationContext成员对象
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }


    /**
     * 定义get方法，参数为class，调用上下文的getBean 对象方法获取容器中的指定对象
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T get(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }

    //同上，参数为对象名
    public static Object get(String name){
        return applicationContext.getBean(name);
    }


    /**
     * 根据propertyName 获取配置文件中的属性名：
     * @propertyName 配置文件属性名全名：例如：aliSendCode.signName
     * @return
     */
    public static String getProperty(String propertyName){
        Environment environment = ApplicationContextUtil.get(Environment.class);
        return environment.getProperty(propertyName);
    }
}
